from datetime import datetime
from typing import Any, Self

from fastapi import APIRouter
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse,Response
from pydantic import BaseModel, field_validator

router = APIRouter()

class Item(BaseModel):
    title: str
    timestamp: datetime
    description: str | None = None

    @field_validator('timestamp', mode='before')
    def validate_timestamp(cls, value):
        if isinstance(value, str):
            return datetime.strptime(value, "%Y-%m-%d %H:%M:%S")
        return value

@router.put("/items/{id}")
async def update_item(id:str,item: Item):
    json_compatible_item_data = jsonable_encoder(item)
    return JSONResponse(content=json_compatible_item_data)

@router.get("/xml")
async def get_xml():
    data = """<?xml version="1.0"?>
    <root>
    <Header>
        这是header部分
    </Header>
    <Body>
        这是body部分
    </Body>
    </root>
    """
    return Response(content=data, media_type="application/xml")

@router.get("/with_header_cookie")
async def with_header_cookie():
    content = {"msg": "这是响应的主体内容"}
    header = {"X-Custom-Header": "this is custom header"}
    resp = JSONResponse(content=content, headers=header)
    resp.set_cookie(key="session_id", value="abc123")
    return resp